package org.geektimes.http.server.jdk.servlet.matcher;

import org.geektimes.commons.util.PriorityComparator;
import org.geektimes.http.server.jdk.servlet.FindSuperClassUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author wenl
 */
public class ComposeURLPatternsMatcher implements URLPatternsMatcher {

    List<URLPatternsMatcher> urlPatternsMatcherList = new ArrayList<>();

    public ComposeURLPatternsMatcher() {
        //利用spring的机制，读取classpath*:org/geektimes/http/server/jdk/servlet/**/*.class 所有的类，填入URLPatternsMatcher，按AntPathURLPatternsMatcher排序
        Consumer<Class> consumer = clazz-> {
            try {
                // 接口，抽象类这里会失败
                URLPatternsMatcher urlPatternsMatcher =  (URLPatternsMatcher) clazz.newInstance();
                urlPatternsMatcherList.add( urlPatternsMatcher );
            } catch ( Exception e ) {
            }
        };
        FindSuperClassUtils.findSubClassAndConsume(URLPatternsMatcher.class,ComposeURLPatternsMatcher.class,consumer);
        urlPatternsMatcherList.sort( PriorityComparator.INSTANCE );
    }

    @Override
    public boolean matches( Collection<String> urlPatterns, String requestURI ) {
        for ( URLPatternsMatcher urlPatternsMatcher : urlPatternsMatcherList ) {
            if ( urlPatternsMatcher.matches( urlPatterns, requestURI ) ) {
                return true;
            }
        }
        return false;
    }
}
